package handlers

import (
	"encoding/hex"
	"fmt"

	"github.com/labstack/echo/v4"
	"gorm.io/gorm"
	"techoiceness.com/aiagent/llm-gateway/internal/agent"
	"techoiceness.com/aiagent/llm-gateway/internal/auth"
	"techoiceness.com/aiagent/llm-gateway/internal/config"
	"techoiceness.com/aiagent/llm-gateway/internal/entity"
	"techoiceness.com/aiagent/llm-gateway/internal/llm"
	"techoiceness.com/aiagent/llm-gateway/internal/repository"
	"techoiceness.com/aiagent/llm-gateway/internal/server/handlers/admin"
	"techoiceness.com/aiagent/llm-gateway/internal/server/handlers/user"
	"techoiceness.com/aiagent/llm-gateway/internal/tools"
)

// RootHandler 根 Handler
type RootHandler struct {
	cfg *config.Config
	db  *gorm.DB

	jwtManager *auth.JWTManager

	// Repository容器统一管理所有repository
	repos repository.ContainerInterface

	llmProviderManager *llm.ProviderManager
	toolManager        *tools.ToolManager
	agentHub           *agent.AgentHub
}

// NewRootHandler 创建根 Handler
func NewRootHandler(cfg *config.Config, db *gorm.DB) (*RootHandler, error) {
	h := &RootHandler{
		cfg: cfg,
		db:  db,
	}

	if err := h.initDependencies(); err != nil {
		return nil, fmt.Errorf("初始化依赖失败: %w", err)
	}

	return h, nil
}

// initDependencies 初始化所有依赖
func (h *RootHandler) initDependencies() error {
	// 初始化JWT管理器
	jwtSecretBytes, err := hex.DecodeString(h.cfg.Server.JWTSecret)
	if err != nil {
		return fmt.Errorf("解码JWT密钥失败: %w", err)
	}
	jwtManager, err := auth.NewJWTManager(jwtSecretBytes)
	if err != nil {
		return fmt.Errorf("初始化JWT管理器失败: %w", err)
	}
	h.jwtManager = jwtManager

	// 初始化Repository容器
	h.repos = repository.NewContainer(h.db)

	// 初始化 LLM Provider 管理器
	llmProviderManager := llm.NewProviderManager(h.repos.GetLLMProvider())
	h.llmProviderManager = llmProviderManager

	// 初始化工具管理器 (必须在 agentHub 之前初始化)
	toolManager := tools.NewToolManager(h.repos.GetTool())
	h.toolManager = toolManager

	// 初始化 agent hub
	agentHub := agent.NewAgentHub(
		agent.WithRepository(h.repos.GetLLMMessage()),
		agent.WithProviderManager(llmProviderManager),
		agent.WithToolManager(h.toolManager),
	)
	h.agentHub = agentHub

	// 初始化内置工具
	h.initBuiltinTools()
	return nil
}

// initBuiltinTools 初始化内置工具
func (h *RootHandler) initBuiltinTools() {
	// 注册内置工具
	h.toolManager.RegisterTool(tools.NewHTTPClientTool())
	h.toolManager.RegisterTool(tools.NewTimeTool())

	postgreSQLTool := tools.NewPostgreSQLTool(h.repos.GetTool())
	h.toolManager.RegisterTool(postgreSQLTool)
}

// RegisterRoutes 注册所有handler的路由
func (h *RootHandler) RegisterRoutes(e *echo.Echo) {
	// API路由组
	api := e.Group("/api")

	authMiddleware := auth.NewAuthMiddleware(h.jwtManager, h.db)

	userHandler := user.NewUserHandler(h.cfg, h.jwtManager, h.llmProviderManager, h.agentHub, h.repos)

	// 注册用户相关路由 - 使用User实体认证
	userHandler.RegisterRoutes(api, authMiddleware, func() auth.Authenticatable {
		return &entity.User{}
	})

	// 注册管理员相关路由 - 使用Admin实体认证
	adminHandler := admin.NewAdminHandler(h.jwtManager, h.agentHub, h.llmProviderManager, h.toolManager, h.repos)
	adminHandler.RegisterRoutes(api, authMiddleware, func() auth.Authenticatable {
		return &entity.Admin{}
	})
}
